#include "serial_port.h"




Serial_Port::Serial_Port(QString port_name, int baudrate)
{
    serial_port = nullptr;

    if(open_serial_port(port_name,baudrate))
    {
        qDebug() << "open Serial_Port: "+port_name;
    }
    else
    {

    }

}

Serial_Port::~Serial_Port()
{
    close_serial_port();
    serial_port = nullptr;

    qDebug() << "delete Serial_Port";
}


//打开串口
bool Serial_Port::open_serial_port(QString port_name, int baudrate)
{
    serial_port = nullptr;

    serial_port = new QSerialPort();

    if(serial_port)
    {
        if(QFile::exists(port_name))
        {
            serial_port->setPortName(port_name);

            if(serial_port->open(QIODevice::ReadWrite))
            {
                serial_port->setBaudRate(baudrate,QSerialPort::AllDirections);
                serial_port->setDataBits(QSerialPort::Data8);
                serial_port->setParity(QSerialPort::NoParity);
                serial_port->setFlowControl(QSerialPort::NoFlowControl);
                serial_port->setStopBits(QSerialPort::OneStop);

                serial_port->setReadBufferSize(0);

                connect(serial_port,SIGNAL(readyRead()),this,SLOT(slot_read_serial_port()));
                connect(serial_port,SIGNAL(bytesWritten(qint64)),this,SLOT(slot_byteswriten_serial_port(qint64)));

                serial_port_tx_queue = new Circle_queue();
                serial_port_rx_queue = new Circle_queue();

                return true;
            }
            else
            {
                return false;
            }
        }else return false;
    }

    return false;
}

bool Serial_Port::close_serial_port(void)
{
    if(serial_port->isOpen())
    {
        serial_port->close();
    }
    delete serial_port;
    delete serial_port_tx_queue;
    delete serial_port_rx_queue;
    return true;
}

void Serial_Port::slot_byteswriten_serial_port(qint64 bytes)
{
    //qDebug() << "slot_byteswriten_serial_port" << bytes;
    emit signal_byteswritten(bytes);
}

//写串口数据
void Serial_Port::slot_write_serial_port(char *p_data,int len)
{
    //qDebug() << ">>> slot_write_srial_port >>>" << len;

    if(serial_port->isOpen())
    {
        if(len)serial_port->write(p_data,len);
    }

    QByteArray ba_data((char*)p_data,(int)len);
    QString str_data = ba_data.toHex();

    qDebug() << str_data << ", len = " << len;
}


//read serial port data
int Serial_Port::slot_read_serial_port()
{
    int recv_len = 0;
    QByteArray recv_data;

    //qDebug() << ">>> slot_read_serial_port >>>";

    recv_data = serial_port->readAll();            //读取串口数据

    serial_port_rx_queue->circlebuff_write_packet_data(recv_data.data(),(unsigned int)recv_data.count());

    emit read_serial_signals();

    return recv_len;
}


